package com.ksd.web.controller.system;

import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.core.controller.BaseController;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.enums.SourceTypeEnum;
import com.ksd.common.excel.*;
import com.ksd.common.utils.DateUtils;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.service.MovieExcelService;
import com.ksd.quartz.service.MusicExcelService;
import com.ksd.system.domain.*;
import com.ksd.system.service.*;
import com.ksd.web.controller.domain.UploadFileObjec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
public class FileTreeUsbController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(FileTreeUsbController.class);
    @Autowired
    private ISysOperLogService sysOperLogService;
    @Autowired
    private ISysMovieService sysMovieService;
    @Autowired
    private ISysMusicDataService sysMusicDataService;
    @Autowired
    private ISysBatchService sysBatchService;
    @Autowired
    private MovieExcelService movieExcelService;
    @Autowired
    private MusicExcelService musicExcelService;

    private Map<String, Integer> uploadProgressMap = new HashMap<>();
    private Map<String, Integer> uploadProgressTotalMap = new HashMap<>();


    @PostMapping("/hardDisk/startUpload")
    public AjaxResult hardDisk(@Validated @RequestBody UploadFileObjec uploadFileObjec) {
        logger.info("硬盘/data路径下的文件导入");
        //校验选择的文件与内容类型是否匹配
        //解析上传文件的所有符合条件名称的Excel文件,解析该文件,判断该文件是电影还是歌曲的Excel导入表格
        //选中指定的Excel文件,通过读取Excel文件,找到待导入的内容文件
        List<String> filePathsChoose = uploadFileObjec.getFilePaths();
        logger.info("前端选中的文件个数:"+filePathsChoose.size());
//        sysOperLogService.insertOperlogSuccess("前端选中的文件个数:"+filePathsChoose.size());
        Integer excelInertCount = 0;
        ArrayList<MovieExcel> movieExcelList = new ArrayList<>();
        ArrayList<MusicExcel> musicExcelList = new ArrayList<>();

        String hardDiskFilePath = PlayControlConfig.getHardDiskFilePath();
        LinkedHashSet<String> movieExcelFiles = ExcelFileFinder.findMovieExcelFiles(hardDiskFilePath);
        LinkedHashSet<String> musicExcelFiles = ExcelFileFinder.findMusicExcelFiles(hardDiskFilePath);

        //开始读取选中的excel文件,解析获取里面的数据,计算个数
        for (String movieExcelFile : movieExcelFiles) {
            List<MovieExcel> movieExcels = ExcelReader.readExcelMovieFile(new File(movieExcelFile));
            excelInertCount += movieExcels.size();
            movieExcelList.addAll(movieExcels);
        }

        for (String musicExcelFile : musicExcelFiles) {
            List<MusicExcel> musicExcels = ExcelReader.readExcelMusicFile(new File(musicExcelFile));
            excelInertCount += musicExcels.size();
            musicExcelList.addAll(musicExcels);
        }

        logger.info("查询解析到的符合条件的待导入的数据:歌曲:"+musicExcelList.size()+",电影:"+movieExcelList.size());
        sysOperLogService.insertOperlogSuccess("查询解析到的符合条件的待导入的数据:歌曲:"+musicExcelList.size()+",电影:"+movieExcelList.size());
        logger.info("总个数:"+excelInertCount);

        String taskId = "";
        SysBatch result = new SysBatch();
        do {
            taskId = UUID.randomUUID().toString();
            result.setTaskId(taskId);
            sysBatchService.selectSysBatchList(result);
            result = sysBatchService.selectSysBatchByTaskId(taskId);
        }while (StringUtils.isNotNull(result));
        uploadProgressMap.put(taskId, 0);
        uploadProgressTotalMap.put(taskId, 0);
        String userName = getLoginUser().getUser().getUserName();


        Integer finalExcelFileCount = excelInertCount;
        String finalTaskId = taskId;
        new Thread(() -> {
            int uploadedFilesCount = 0;
                logger.info("待解析的文件:"+hardDiskFilePath);
                if (movieExcelFiles != null && movieExcelFiles.size() > 0) {
                    SysBatch sysBatchSql = new SysBatch();
                    sysBatchSql.setTaskId(finalTaskId);
                    sysBatchSql.setType(SysTvType.movieDefaultId);
                    List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchSql);
                    if (sysBatches.size() == 0) {
                        sysBatchSql.setUserName(userName);
                        sysBatchSql.setStartTime(new Date());
                        sysBatchService.insertSysBatch(sysBatchSql);
                    }
                }
                //开始读取选中的excel文件,解析获取里面的数据,计算个数
                for (String movieExcelFile : movieExcelFiles) {
                    logger.info("开始录入磁盘内的电影的Excel数据:"+movieExcelFile);
                    File excelFile = new File(movieExcelFile);
                    if (excelFile.exists()) {
                        List<MovieExcel> movieExcels = ExcelReader.readExcelMovieFile(excelFile);
                        logger.info("磁盘查询到待录入的电影个数:"+movieExcels.size());
                        if (movieExcels.size() > 0){
                            movieExcelService.insertReadExcelByRootPath(excelFile.getParent(),movieExcels,finalTaskId,SourceTypeEnum.disk.getCode());
                            uploadedFilesCount = uploadedFilesCount + movieExcels.size();
                            int progress = (int) ((uploadedFilesCount / (double) finalExcelFileCount) * 100);
                            logger.info("磁盘电影计算进度 progress:"+progress+" ,总数:"+ finalExcelFileCount +",已上传入库:"+uploadedFilesCount);
                            uploadProgressMap.put(finalTaskId, progress);
                        }

                        //标记Excel文件已录入
                        try {
                            changeExceFile(excelFile);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }

                if (musicExcelFiles != null && musicExcelFiles.size() > 0) {
                    SysBatch sysBatchSql = new SysBatch();
                    sysBatchSql.setTaskId(finalTaskId);
                    sysBatchSql.setType(SysTvType.songDefaultId);
                    List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchSql);
                    if (sysBatches.size() == 0) {
                        sysBatchSql.setUserName(userName);
                        sysBatchSql.setStartTime(new Date());
                        sysBatchService.insertSysBatch(sysBatchSql);
                    }
                }
                for (String musicExcelFile : musicExcelFiles) {
                    logger.info("开始录入磁盘内的歌曲Excel数据:"+musicExcelFile);
                    File excelFile = new File(musicExcelFile);
                    if (excelFile.exists()) {
                        List<MusicExcel> musicExcels = ExcelReader.readExcelMusicFile(excelFile);
                        logger.info("磁盘查询到待录入的歌曲个数:"+musicExcels.size());
                        if (musicExcels.size() > 0){
                            musicExcelService.insertReadExcelByRootPath(excelFile.getParent(),musicExcels,finalTaskId, SourceTypeEnum.disk.getCode());
                            uploadedFilesCount = uploadedFilesCount + musicExcels.size();
                            int progress = (int) ((uploadedFilesCount / (double) finalExcelFileCount) * 100);
                            logger.info("磁盘歌曲计算进度 progress:"+progress+" ,总数:"+ finalExcelFileCount +",已上传入库:"+uploadedFilesCount);
                            uploadProgressMap.put(finalTaskId, progress);
                        }
                        //标记Excel文件已录入
                        try {
                            changeExceFile(excelFile);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }

        }).start();

        return AjaxResult.success("文件上传进度taskId: "+taskId,taskId);
    }

    public void changeExceFile(File excelFile) throws IOException {
        String absolutePath = excelFile.getParentFile().getAbsolutePath();
        String fileName = excelFile.getName();
        String newFilePath = absolutePath + File.separator + "已入库_" + fileName + ".bak_" + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
        Path newPath = Paths.get(newFilePath);
        Path originalPath = Paths.get(excelFile.getAbsolutePath());
        logger.info("修改Excel文件,标记已录入文件:"+newFilePath);
        Files.move(originalPath, newPath);
    }
    @PostMapping("/usb/startUpload")
    public AjaxResult startUpload(@Validated @RequestBody UploadFileObjec uploadFileObjec) {
        /**
         * 选中的文件夹里面包含的文件有:config.xml,海报图片,推荐图片,视频,或歌曲,歌词,专辑图片
         * 读取config.xml文件里的内容,将视频,海报图片,推荐图片,都安放在指定目录下.
         * 同时读取文件分类和视频类型,配置对应的value值
         */
//        System.out.println("USB导入内容分类:"+uploadFileObjec.getFileType());
//        String fileType = uploadFileObjec.getFileType();
        //校验选择的文件与内容类型是否匹配
        //解析上传文件的所有符合条件名称的Excel文件,解析该文件,判断该文件是电影还是歌曲的Excel导入表格
        //选中指定的Excel文件,通过读取Excel文件,找到待导入的内容文件
        List<String> filePathsChoose = uploadFileObjec.getFilePaths();
        logger.info("前端选中的文件个数:"+filePathsChoose.size());
        sysOperLogService.insertOperlogSuccess("前端选中的文件个数:"+filePathsChoose.size());
        Integer excelInertCount = 0;
        ArrayList<MovieExcel> movieExcelList = new ArrayList<>();
        ArrayList<MusicExcel> musicExcelList = new ArrayList<>();

        for (String filePath : filePathsChoose) {
            logger.info("待解析的文件:"+filePath);
            sysOperLogService.insertOperlogSuccess("待解析的文件:"+filePath);
            LinkedHashSet<String> movieExcelFiles = ExcelTool.findMovieExcelFiles(filePath);
            //开始读取选中的excel文件,解析获取里面的数据,计算个数
            for (String movieExcelFile : movieExcelFiles) {
                List<MovieExcel> movieExcels = ExcelReader.readExcelMovieFile(new File(movieExcelFile));
                excelInertCount += movieExcels.size();
                movieExcelList.addAll(movieExcels);
            }

            LinkedHashSet<String> musicExcelFiles = ExcelTool.findMusicExcelFiles(filePath);
            for (String musicExcelFile : musicExcelFiles) {
                List<MusicExcel> musicExcels = ExcelReader.readExcelMusicFile(new File(musicExcelFile));
                excelInertCount += musicExcels.size();
                musicExcelList.addAll(musicExcels);
            }
        }

        logger.info("查询解析到的符合条件的待导入的数据:歌曲:"+musicExcelList.size()+",电影:"+movieExcelList.size());
        sysOperLogService.insertOperlogSuccess("查询解析到的符合条件的待导入的数据:歌曲:"+musicExcelList.size()+",电影:"+movieExcelList.size());
        logger.info("总个数:"+excelInertCount);

        String taskId = "";
        SysBatch result = new SysBatch();
        do {
            taskId = UUID.randomUUID().toString();
            result.setTaskId(taskId);
            sysBatchService.selectSysBatchList(result);
            result = sysBatchService.selectSysBatchByTaskId(taskId);
        }while (StringUtils.isNotNull(result));
        uploadProgressMap.put(taskId, 0);
        uploadProgressTotalMap.put(taskId, 0);
        String userName = getLoginUser().getUser().getUserName();


        Integer finalExcelFileCount = excelInertCount;
        String finalTaskId = taskId;
        new Thread(() -> {
            int uploadedFilesCount = 0;

            for (String filePath : filePathsChoose) {
                logger.info("当前页面在U盘内选中的Excel待解析的文件:"+filePath);
                File file = new File(filePath);
                String usbDirPath = file.getParent();
                logger.info("当前页面在U盘内选择的Excel文件的根目录:"+usbDirPath);
                LinkedHashSet<String> movieExcelFiles = ExcelTool.findMovieExcelFiles(filePath);
                if (movieExcelFiles != null && movieExcelFiles.size() > 0) {
                    SysBatch sysBatchSql = new SysBatch();
                    sysBatchSql.setTaskId(finalTaskId);
                    sysBatchSql.setType(SysTvType.movieDefaultId);
                    List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchSql);
                    if (sysBatches.size() == 0) {
                        sysBatchSql.setUserName(userName);
                        sysBatchSql.setStartTime(new Date());
                        sysBatchService.insertSysBatch(sysBatchSql);
                    }
                }
                //开始读取选中的excel文件,解析获取里面的数据,计算个数
                for (String movieExcelFile : movieExcelFiles) {
                    logger.info("开始录入U盘内的电影Excel数据:"+movieExcelFile);
                    List<MovieExcel> movieExcels = ExcelReader.readExcelMovieFile(new File(movieExcelFile));
                    for (MovieExcel movieExcel : movieExcels) {
                        movieExcelService.copyUsbInsertByDirPath(usbDirPath,movieExcel,finalTaskId);
                        uploadedFilesCount ++;
                        int progress = (int) ((uploadedFilesCount / (double) finalExcelFileCount) * 100);
                        logger.info("电影计算进度 progress:"+progress+" ,总数:"+ finalExcelFileCount +",已上传入库:"+uploadedFilesCount);
                        uploadProgressMap.put(finalTaskId, progress);
                    }

                    try {
                        changeExceFile(new File(movieExcelFile));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                }

                LinkedHashSet<String> musicExcelFiles = ExcelTool.findMusicExcelFiles(filePath);
                if (musicExcelFiles != null && musicExcelFiles.size() > 0) {
                    SysBatch sysBatchSql = new SysBatch();
                    sysBatchSql.setTaskId(finalTaskId);
                    sysBatchSql.setType(SysTvType.songDefaultId);
                    List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchSql);
                    if (sysBatches.size() == 0) {
                        sysBatchSql.setUserName(userName);
                        sysBatchSql.setStartTime(new Date());
                        sysBatchService.insertSysBatch(sysBatchSql);
                    }
                }
                for (String musicExcelFile : musicExcelFiles) {
                    logger.info("开始录入U盘内的歌曲Excel数据:"+musicExcelFile);
                    List<MusicExcel> musicExcels = ExcelReader.readExcelMusicFile(new File(musicExcelFile));
                    for (MusicExcel musicExcel : musicExcels) {
                        musicExcelService.copyUsbInsertByDirPath(usbDirPath,musicExcel,finalTaskId);
                        uploadedFilesCount ++;
                        int progress = (int) ((uploadedFilesCount / (double) finalExcelFileCount) * 100);
                        logger.info("歌曲计算进度 progress:"+progress+" ,总数:"+ finalExcelFileCount +",已上传入库:"+uploadedFilesCount);
                        uploadProgressMap.put(finalTaskId, progress);
                    }

                    try {
                        changeExceFile(new File(musicExcelFile));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }


            }

        }).start();

        return AjaxResult.success("文件上传进度taskId: "+taskId,taskId);
    }

    @GetMapping("/usb/uploadProgress/{taskId}")
    public Map<String, Integer> getUploadProgress(@PathVariable String taskId) {
        Map<String, Integer> response = new HashMap<>();
        Integer progress = uploadProgressMap.getOrDefault(taskId, 0);
        response.put("progress", progress);

        Integer total = uploadProgressTotalMap.getOrDefault(taskId, 0);
        response.put("total", total);
        if (progress == 100) {
            SysBatch sysBatchTemp = new SysBatch();
            sysBatchTemp.setTaskId(taskId);
            List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchTemp);
            logger.info("此次U盘的批次记录:"+sysBatches.size()+"========taskId:"+taskId);
            for (SysBatch sysBatch : sysBatches) {
            String type = sysBatch.getType();
                if (type.equals(SysTvType.movieDefaultId)){
                    SysMovie sysMovie = new SysMovie();
                    sysMovie.setTaskId(taskId);
                    List<SysMovie> movieList = sysMovieService.selectSysMovieList(sysMovie);
                    logger.info("U盘挂载导入电影:"+movieList.size());
                    if (movieList.size() != 0) {
                        sysBatch.setStatus("0");
                        sysBatch.setNumber(String.valueOf(movieList.size()));
                        sysBatch.setEndTime(new Date());
                        sysBatch.setContentEnd(movieList.get(0).getId().toString());
                        sysBatch.setContentStart(movieList.get(movieList.size() - 1).getId().toString());
                        sysBatch.setRemake("U盘挂载导入");
                        sysOperLogService.insertOperlogApiSuccess("通过服务器上U盘挂载上传电影内容的批次记录更新");
                        sysBatchService.updateSysBatch(sysBatch);
                    }
                }else if(type.equals(SysTvType.songDefaultId)){
                    SysMusicData sysMusicData = new SysMusicData();
                    sysMusicData.setTaskId(taskId);
                    List<SysMusicData> sysMusicDataList = sysMusicDataService.selectSysMusicDataList(sysMusicData);
                    logger.info("U盘挂载导入歌曲:"+sysMusicDataList.size());
                    if (sysMusicDataList.size() != 0){
                        sysBatch.setStatus("0");
                        sysBatch.setNumber(String.valueOf(sysMusicDataList.size()));
                        sysBatch.setEndTime(new Date());
                        sysBatch.setContentEnd(sysMusicDataList.get(0).getId().toString());
                        sysBatch.setContentStart(sysMusicDataList.get(sysMusicDataList.size() - 1).getId().toString());
                        sysBatch.setRemake("U盘挂载导入");
                        sysOperLogService.insertOperlogApiSuccess("通过服务器上U盘挂载上传歌曲内容的批次记录更新");
                        sysBatchService.updateSysBatch(sysBatch);
                    }
                }
            }

        }
        return response;
    }
}